﻿using Furion.EventBus;

namespace Events;

public class MonthProduct : IEventSubscriber, ISingleton
{
    private readonly ISqlSugarClient db;

    private readonly Common com;

    public MonthProduct(ISqlSugarClient db, Common com)
    {
        this.db = db;
        this.com = com;
    }

    /// <summary>
    /// 支付成功设置快递信息
    /// </summary>
    /// <returns></returns>
    [EventSubscribe("OrderComplete")]
    public async Task SetExpress(EventHandlerContext e)
    {
        var data = e.Source.Payload as Dto.OrderComplete;

        var order = await com.GetOrder(data.OrderNo);

        var orderExt = await db.Queryable<Entity.Orders.Order_Ext_MonthProduct>().FirstAsync(x => x.OrderId == order.Id);

        if (orderExt == null || orderExt.ExpressId > 0) return;

        var express = new Entity.Express
        {
            AddressId = orderExt.AddressId,

            UserId = orderExt.UserId
        };

        int expressId = await db.Insertable(express).ExecuteReturnIdentityAsync();

        orderExt.ExpressId = expressId;

        await db.Updateable(orderExt).ExecuteCommandHasChangeAsync();
    }
}
